# encoding=utf-8
# 此脚本用于测定Host-Pico-AIpro的相关稳定运行参数
import time
import usb.core
import usb.util

VID = 0xF055
PID = 0x9999

# find our device
dev = usb.core.find(idVendor=VID, idProduct=PID)

# was it found?
if dev is None:
    raise ValueError('Device not found')

# get an endpoint instance
cfg = dev.get_active_configuration()
intf = cfg[(0, 0)]

outep = usb.util.find_descriptor(
    intf,
    # match the first OUT endpoint
    custom_match= \
        lambda e: \
            usb.util.endpoint_direction(e.bEndpointAddress) == \
            usb.util.ENDPOINT_OUT)

inep = usb.util.find_descriptor(
    intf,
    # match the first IN endpoint
    custom_match= \
        lambda e: \
            usb.util.endpoint_direction(e.bEndpointAddress) == \
            usb.util.ENDPOINT_IN)

assert inep is not None
assert outep is not None


def generate_byte(start_idx: int, end_idx: int, step: int):
    byte_array = bytearray(step)
    for i in range(start_idx, end_idx + 1):
        byte_array[i % step] = i % 256
    return byte_array


def generate_str(start_idx: int, end_idx: int, step: int):
    byte_array = ['0'] * step
    for i in range(start_idx, end_idx + 1):
        byte_array[i % step] = str(i % 256)
    return '_'.join(byte_array)


def generate_array(start_idx: int, end_idx: int, step: int, gen_str: bool = True):
    if gen_str:
        return generate_str(start_idx, end_idx, step)
    else:
        return generate_byte(start_idx, end_idx, step)


s = 12
b_list = [generate_array(i * s, i * s + s - 1, s) for i in range(256 // s)]
for b in b_list:
    """
        Ai Pro Spi跨机测试得到特性:
            在5000*1000的速度下，常规杜邦线，缓存大小48Byte，大约跨机速度0.12MB/s
            1. 信号发出到从机大概2ms，需要手动sleep以保证数据接收
            2. 相对稳定的数据传输格式:
                - 空格，int32_1, int32_2, int32_3, int32_4, uint8:
                    - 空格将数据整体右移
                    - 后续为int32长度的数据包编号
                    - uint8为后面有效的Byte个数
                - 剩余(48 - 6) 为Byte的数据
            
    """
    d = " {}".format(b)
    print("next will be wirte: {}, len: {}".format(d, len(d)))
    try:
        outep.write(d)
    except Exception as e:
        print("write fail")
    # a = input("input to next")
    try:
        from_device = inep.read(len(d))
        print("Device Says: {}".format(''.join([chr(x) for x in from_device])))
    except Exception as e:
        print("next")
    # time.sleep(0.01)
